//
//  OrderPayViewController.m
//  EasyToTesco
//
//  Created by mc on 16/2/23.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "OrderPayViewController.h"
#import "HeaderFileForEasyToTesco.h"
#import "OrderPayTableViewCell.h"
#import "AFNetworking.h"
#import "PayOrderTwoTableViewCell.h"
#import "ReadLoginData.h"
#import "RKAlertView.h"

@interface OrderPayViewController ()<UITableViewDataSource, UITableViewDelegate,UIAlertViewDelegate>{
        NSString *orderNum;
    
    NSMutableArray *boolArray;
    
    
    
}



@property(nonatomic, strong)UITableView *OrderPayTableView;

@property (nonatomic,copy)NSString *paymethod;

@property (nonatomic,copy)NSString *pwd;
@property (nonatomic,copy)NSString *password;

@property (nonatomic,strong)NSArray *titleArray;

@property(nonatomic,copy)NSString *payNum;
@property(nonatomic,strong)NSDictionary *payDict;

@end

@implementation OrderPayViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //初始化
    [self addOrderPayInit];
    
    //添加顶部视图
    [self addOrderPayTopview];
    
    //添加UI
    [self addOrderPayUI];
    
    //添加Tableview
    [self addOrderPayTableview];
    self.paymethod = @"2";
    [self loadUserData];
    NSLog(@"%@",self.jine);

}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 111111) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)addOrderPayInit {
    
    orderNum = @"2010310973816736175315";
//   imageArray = @[@"微信", @"支付宝", @"银联", @"信用卡", @"货到付款"];
    boolArray = [NSMutableArray arrayWithObjects:@"1",@"0", @"0", nil];
    self.titleArray = @[@"积分支付", @"余额支付"];
}

- (void)addOrderPayUI {
    
}

- (void)addOrderPayTableview {
    self.OrderPayTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.9) style:UITableViewStyleGrouped];
    self.OrderPayTableView.dataSource = self;
    self.OrderPayTableView.delegate = self;
    [self.view addSubview:self.OrderPayTableView];
}

-(void)addOrderPayTopview {
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"订单支付";

}

- (void)gobackClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return self.titleArray.count;
    }else{
         return self.titleArray.count;
    }

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"OrderPayTableViewCell";
        OrderPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderPayTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
//        if (indexPath.row == 0) {
            cell.OrderPayPriceLabel.textColor = [UIColor redColor];
            cell.OrderPayPriceLabel.font = [UIFont systemFontOfSize:12];
            cell.OrderPayNamelabel.text = @"订单金额";
//        }else if (indexPath.row == 1) {
//            
//        }else if (indexPath.row == 2) {
//            cell.OrderPayNamelabel.textColor = [UIColor grayColor];
//            cell.OrderPayPriceLabel.textColor = [UIColor grayColor];
//            cell.OrderPayNamelabel.text = @"优惠价已支付";
//        }else if (indexPath.row == 3) {
//            cell.OrderPayNamelabel.textColor = [UIColor grayColor];
//            cell.OrderPayPriceLabel.textColor = [UIColor grayColor];
//            cell.OrderPayNamelabel.text = @"积分已支付";
//        }else{
//            cell.OrderPayPriceLabel.textColor = [UIColor grayColor];
//            cell.OrderPayNamelabel.text = @"您已支付";
//        }
//        @"¥%.2f", [self.jine floatValue]
        cell.OrderPayPriceLabel.text = [NSString stringWithFormat:@"%@",self.jine];
        
        return cell;
    } else {
        
        static NSString *identifier = @"PayOrderTwoTableViewCell";
        PayOrderTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"PayOrderTwoTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.paySelectView.layer.borderWidth = 2;
            cell.paySelectView.layer.cornerRadius = CGRectGetHeight(cell.paySelectView.frame)/2;
            cell.paySelectView.layer.masksToBounds = YES;
            
            
           
        }
        cell.PayTwoTitleLabel.text = [NSString stringWithFormat:@"%@", self.titleArray[indexPath.row]];
        
        if ([boolArray[indexPath.row] isEqualToString:@"1"]) {
            cell.paySelectView.backgroundColor = [UIColor greenColor];
        } else {
            cell.paySelectView.backgroundColor = [UIColor whiteColor];
        }
        
                return cell;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return 30;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
     UIView *headerView = [[UIView alloc] init];
    headerView.layer.borderWidth = 1;
    headerView.layer.borderColor = [UIColor colorWithRed:244/255. green:244/255. blue:244/255. alpha:1].CGColor;
    if (section == 0) {
        headerView.backgroundColor = [UIColor whiteColor];
    } else {
        UILabel *titlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 80, 20)];
        titlabel.text = @"支付方式";
        titlabel.font = [UIFont systemFontOfSize:12];
        [headerView addSubview:titlabel];
    }
   
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 40;
    } else {
        return 50;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 30;
    } else {
        return 60;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc] init];
    if (section == 0) {
        UILabel *MoneyLabel = [[UILabel alloc] initWithFrame:CGRectMake(WEITH-80, 5, 80, 20)];
        MoneyLabel.textColor =[UIColor redColor];
        MoneyLabel.font = [UIFont systemFontOfSize:13];
//        :@"¥%.2f", [self.jine floatValue]
        MoneyLabel.text = [NSString stringWithFormat:@""];
        [footView addSubview:MoneyLabel];
        
        UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(MoneyLabel.frame)-60,5, 60, 20)];
        testLabel.font = [UIFont systemFontOfSize:12];
        testLabel.text = @" ";
        [footView addSubview:testLabel];
        
    }else {
        UIButton *GoPayMentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        GoPayMentBtn.frame = CGRectMake(30, 10, WEITH-60, 40);
        GoPayMentBtn.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
        [GoPayMentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        GoPayMentBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        GoPayMentBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [GoPayMentBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [GoPayMentBtn addTarget:self action:@selector(GoPayMentBtnClick) forControlEvents:UIControlEventTouchUpInside];
        GoPayMentBtn.layer.cornerRadius = 6;
        GoPayMentBtn.layer.masksToBounds = YES;
        [footView addSubview:GoPayMentBtn];
    }
    return footView;
}

- (void)GoPayMentBtnClick{
    if (self.paymethod.length == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还没有选择您的支付方式" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
        self.paymethod = @"1";
    } else {
        
        
        NSLog(@"%@",self.paymethod);
        
//        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"您选择支付方式是%@", self.paymethod] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alview show];
    }
    
    [RKAlertView showAlertPlainTextWithTitle:@"请输入二级密码" message:nil cancelTitle:@"取消" confirmTitle:@"确认" alertViewStyle:UIAlertViewStylePlainTextInput confrimBlock:^(UIAlertView *alertView) {
        NSLog(@"确认了输入：%@",[alertView textFieldAtIndex:0].text);
        self.pwd = [alertView textFieldAtIndex:0].text;
        
        if (![self.pwd isEqualToString:self.password]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"输入密码错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
//            [alert ]
        } else {
            [self zhifudingdanbuttondianjishijian];
        }
        
        
        
    } cancelBlock:^{
        //       NSLog(@"取消了");
    }];
    
    
}

/*
    phone = 18000000000,
	province = 北京市,
	city = 北京市,
	county = 东城区,
	address = Guangzhou,
	postcode = 123412532,
	zt = 1,
	re_id = 131,
	name = 123

 */

#warning 支付逻辑

- (void)loadUserData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    NSString *username = [dict[@"data"] objectForKey:@"username"];
    NSDictionary *param = @{
                            @"username":username
                            };
    
    [manager POST:@"http://www.ylgw8.com/AppUser/UserInfo" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *dict = [self toArrayOrNSDictionary:responseObject];
        
        NSString *password = [dict[@"data"] objectForKey:@"pwdtwo"];
        
        self.password = password;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}


- (void)zhifudingdanbuttondianjishijian{


    NSDictionary *dic = [ReadLoginData readLoginData];
//
    NSString *paymethod = self.paymethod;
    
    NSString *province = [self.address objectForKey:@"province"];
    NSString *s_province = [province stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *password = self.pwd;
    
    
    NSString *city =[self.address objectForKey:@"city"];
    NSString *s_city = [city stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *county = [self.address objectForKey:@"county"];
    NSString *s_county = [county stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *dzhi = [self.address objectForKey:@"address"];
    NSString *dizhi = [dzhi stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *sshouji = [self.address objectForKey:@"phone"];
   

    NSString *userName = [dic[@"data"] objectForKey:@"username"];

    NSString *shr = [self.address objectForKey:@"name"];
    NSString *shouhuoren = [shr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//
    
//
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
//    NSDictionary *param = @{
//                            @"checked":@"0",
//                            @"paymethod":self.paymethod,
//                            @"password":self.pwd,
//                            @"username":userName,
//                            @"shouhuoren":shouhuoren,
//                            @"￼￼￼￼s_province":s_province,
//                            @"s_city":s_city,
//                            @"s_county":s_county,
//                            @"￼￼dizhi":dizhi,
//                            @"sshouji":sshouji,
//                            @"￼youbian":@"",
//                            @"￼beizhu":@""
//                            };
    NSString *url = [NSString stringWithFormat:@"http://www.ylgw8.com/AppShopOrder/AddOrder?checked=0&paymethod=%@&password=%@&username=%@&shouhuoren=%@&s_province=%@&s_city=%@&s_county=%@&dizhi=%@&sshouji=%@&youbian=&beizhu=",paymethod,password,userName,shouhuoren,s_province,s_city,s_county,dizhi,sshouji];
//
//    url = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",[self toArrayOrNSDictionary:responseObject]);
        
        NSDictionary *dict = [self toArrayOrNSDictionary:responseObject];
        
        if ([[dict objectForKey:@"status"] isEqualToNumber:[NSNumber numberWithInt:1]]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"购买成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%@",[dict objectForKey:@"info"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];

        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];

    
}

- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        NSLog(@"%@", self.titleArray[indexPath.row]);
        for (NSInteger i=0; i<boolArray.count; i++) {
            if (indexPath.row == i) {
                boolArray[i] = @"1";
            }else{
                boolArray[i] = @"0";
            }
        }
        
        if (indexPath.row == 0) {
            self.paymethod = @"2";
        } else  {
            self.paymethod = @"1";
        }
    }
    NSLog(@"%@",self.paymethod);
    [self.OrderPayTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
